import { defineEventHandler } from 'h3'
import { getPool } from '../../util/mysql'

export async function checkAdminKey(event: any) {
  const provided = (event.node.req.headers['x-admin-key'] || event.node.req.headers['x-admin-key'.toLowerCase()]) as string | undefined
  const envKey = process.env.ADMIN_KEY || ''
  if (!envKey) {
    event.node.res.statusCode = 500
    return { ok: false, message: 'ADMIN_KEY not configured on server' }
  }
  if (!provided || provided !== envKey) {
    event.node.res.statusCode = 401
    return { ok: false, message: 'unauthorized' }
  }
  return { ok: true }
}

export function parsePaging(event: any) {
  const url = event.node.req.url || ''
  const qp = new URL('http://localhost' + url).searchParams
  const page = Math.max(1, Number(qp.get('page') || '1') || 1)
  const pageSize = Math.min(100, Math.max(1, Number(qp.get('pageSize') || '20') || 20))
  const offset = (page - 1) * pageSize
  const search = qp.get('search') || ''
  const start = qp.get('start') || ''
  const end = qp.get('end') || ''
  return { page, pageSize, offset, search, start, end }
}

export async function queryTableCount(pool: any, table: string, where: string, params: any[]) {
  const [rows]: any = await pool.execute(`SELECT COUNT(1) as total FROM ${table} ${where}`, params)
  return rows && rows[0] ? Number(rows[0].total) : 0
}
